package com.stars.empoly.activity

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.graphics.Rect
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.core.net.toUri
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import com.eazypermissions.common.model.PermissionResult
import com.eazypermissions.coroutinespermission.PermissionManager
import com.luck.picture.lib.PictureSelector
import com.qmuiteam.qmui.kotlin.onClick
import com.stars.empoly.adapter.DynamicAdapter
import com.stars.empoly.adapter.OpinionTypeAdapter
import com.stars.empoly.base.MBActivity
import com.stars.empoly.config.MIntentAction
import com.stars.empoly.databinding.ActivityOpinionBinding
import com.stars.empoly.inte.OnUploadCallback
import com.stars.empoly.model.GoodsImgBean
import com.stars.empoly.model.bean.CateTypeBean
import com.stars.empoly.model.bean.UpImgBean
import com.stars.empoly.utils.ChosePhotoUtils
import com.stars.empoly.utils.FileUtils
import com.stars.empoly.utils.OssUtils
import com.stars.empoly.vmodel.OpinionVModel
import com.trailer.base.utils.UiSwitch
import com.trailer.base.utils.UiUtils
import kotlinx.coroutines.launch

/**
 *
 *on 2020/9/24
 */
class OpinionActivity : MBActivity<OpinionVModel, ActivityOpinionBinding>(),
    OnUploadCallback<UpImgBean> {


    private var recordAdapter: DynamicAdapter? = null

    override fun init(savedInstanceState: Bundle?) {
        super.init(savedInstanceState)
        titleBar()?.tvRight?.visibility=View.VISIBLE
        titleBar()?.tvRight?.text="反馈记录"

        //设置分类
        vm.getCategory()
        var adpter = OpinionTypeAdapter()
        binding.recyclerType.adapter = adpter
        vm.categoryBean.observe(this) {

            var list = ArrayList<CateTypeBean>()
            for (item in it) {
                var bean = CateTypeBean(item, false)
                list.add(bean)
            }
            adpter.addData(list)
        }

        adpter.setOnItemClickListener { adapter, view, position ->

            var list = adpter.data

            for ((index, value) in list.withIndex()) {

                if (index == position) {
                    vm.choseTypeName = value.name
                    value.chose = true
                    adpter.notifyItemChanged(position)

                } else {
                    if (value.chose) {
                        value.chose = false
                        adpter.notifyItemChanged(position)
                    }

                }
            }


        }
        //设置图片
        initAdapter()

        vm.type.observe(this) {

            if (it == "1") {//添加
                lifecycleScope.launch {
                    if (PermissionManager.requestPermissions(
                            this@OpinionActivity, 1000,
                            Manifest.permission.CAMERA,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.READ_EXTERNAL_STORAGE
                        ) is PermissionResult.PermissionGranted
                    ) {

                        if (vm.nopath.size < 3) {
                            ChosePhotoUtils.getChosePhoto(context(), 3 - vm.nopath.size)
                        } else {
                            toast("最多选三张")
                        }

                    }

                }
            }

        }



    }

    override fun listeners() {
        super.listeners()
        titleBar()?.tvRight?.onClick {

            UiSwitch.single(context(), RecordActivity::class.java)


        }
    }

    fun initAdapter() {

        val attachement: java.util.ArrayList<GoodsImgBean> = java.util.ArrayList<GoodsImgBean>()

        val bean = GoodsImgBean(-1, "", -1, false)
        attachement.add(bean)

        val left = UiUtils.dp2Px(context(), 3f)
        val itemDecoration: RecyclerView.ItemDecoration = object : RecyclerView.ItemDecoration() {
            override fun getItemOffsets(
                outRect: Rect,
                view: View,
                parent: RecyclerView,
                state: RecyclerView.State
            ) {
                super.getItemOffsets(outRect, view, parent, state)
                val childAdapterPosition = parent.getChildAdapterPosition(view)
                val i = childAdapterPosition % 3
                if (i != 0) {
                    outRect.left = left
                }
                outRect.top = left
            }
        }
        recordAdapter = DynamicAdapter(vm, attachement)

        binding.recyclerView.addItemDecoration(itemDecoration)
        binding.recyclerView.adapter = recordAdapter

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) {
            return
        }
        if (requestCode == MIntentAction.REQUEST_CODE_IMG) {//图片

            val selectList = PictureSelector.obtainMultipleResult(data)
            val list = ArrayList<String>()
            if (null != selectList) {
                for (item in selectList) {

                    if (item.path.contains("content://")) {

                        val cr = this.contentResolver
                        list.add(FileUtils.getFilePathFromContentUri(item.path.toUri(), cr))
                    } else {
                        list.add(item.path)
                    }

//                    //添加一个默认
//                    val bugAttachment = GoodsImgBean(0, "", 0, true)
//                    recordAdapter!!.addData(recordAdapter!!.data.size - 1, bugAttachment)
//                    vm.nopath.add("")
                }

                Log.e("-hhhh-", "list="+list.size )


                OssUtils(this, vm)
                    .setUpLoad("img", list, this)

            }

            return


        }

        if (requestCode == MIntentAction.REQUEST_CODE_CAMERA) {//拍照
            //拍照
            val selectList = PictureSelector.obtainMultipleResult(data) ?: return
            val list = ArrayList<String>()
            if (selectList[0].path.contains("content://")) {

                val cr = this.contentResolver
                list.add(FileUtils.getFilePathFromContentUri(selectList[0].path.toUri(), cr))

            } else {
                list.add(selectList[0].path)
            }
//            if(vm.type==5){
//                //添加一个默认
//                val bugAttachment = GoodsImgBean(0, "", 0, true)
//                recordAdapter!!.addData(recordAdapter!!.data.size - 1, bugAttachment)
//                vm.nopath.add("")
//            }
            OssUtils(this, vm)
                .setUpLoad("img", list, this)


        }

        return


    }


    override fun binding(): ActivityOpinionBinding {
        return ActivityOpinionBinding.inflate(layoutInflater)
    }

    override fun vmClass(): Class<OpinionVModel> {
        return OpinionVModel::class.java
    }

    override fun title(): String? {

        return "意见反馈"
    }

    override fun onUploadSuccess(t: UpImgBean) {

        if (null != t.url) {
            val bugAttachment = GoodsImgBean(0, t.url!!, 0, false)
            recordAdapter!!.addData(recordAdapter!!.data.size - 1, bugAttachment)
            vm.nopath.add(t.url!!)
        }
    }

    override fun onUploadError(error: String?) {
    }



}
